import requests
from urllib.parse import urlencode
import json
import random
from Bean import Bean
import time
import execjs
from hashlib import md5


class Api(object):
    # 首页分类列表
    goods_url = 'https://prod.ggszhg.com/xgt-app/applet/product/search?'
    # 商品详情页面 （需要登录）
    goods_details_url = 'https://prod.ggszhg.com/xgt-app-not-enter/applet/product/detail?'
    # 获取验证码
    img_captcha_url = "https://prod.ggszhg.com/xgt-app/applet/imgCaptcha/getImgCaptcha?"
    # 校验验证码接口
    validate_captcha_url = "https://prod.ggszhg.com/xgt-app/applet/imgCaptcha/validateCaptcha?"
    # 发送验证码
    send_to_mobile_url = "https://prod.ggszhg.com/xgt-app/applet/personalCenter/sendToMobile?"
    # 登录
    login_url = "https://prod.ggszhg.com/xgt-app/applet/personalCenter/login?"

    def __init__(self):
        self.session = requests.session()
        self.headers = {
            "User-Agent": "Mozilla/5.0 (Linux; Android 5.1.1; vivo Xplay5A Build/LMY47V) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/39.0.0.0 Mobile Safari/537.36 MicroMessenger/7.0.10.1580(0x27000A55) Process/appbrand0 NetType/WIFI Language/zh_CN ABI/arm64",
            "content-type": "application/json;charset=utf-8",
        }

        self.proxies = [
            "120.55.39.108:80",
            "39.103.175.42:3128",
            "101.132.111.208:8082",
            "171.12.40.12:9999",
        ]

    def get_sign(self, t1, t2):
        with open("../js/sign.js", 'r') as file:
            content = file.read()
            result = execjs.compile(content).call('getSign', t1, t2)
            file.close()
        return md5(result.encode('utf8')).hexdigest().upper()

    def get_base_params(self, body_params={}, user_id="", user_token=""):
        params = {"os": "APPLET", "osVersion": "1.0.0", "userId": user_id, "userToken": user_token}
        sign = self.get_sign(params, body_params)
        params['sign'] = sign
        print(sign)
        return params

    def get_goods(self, body_data, user_id="", user_token=""):
        params = self.get_base_params(body_data, user_id, user_token)
        url = self.goods_url + urlencode(params)
        json_obj = json.dumps(body_data)
        pro = random.choice(self.proxies)
        print(pro)
        result = self.session.post(url, data=json_obj, headers=self.headers, verify=False)
        return json.loads(result.text)

    # 检查是否有货
    def check_goods_has(self):
        bean = Bean()
        hasGoods = []
        for item in bean.get_goods_list():
            goods = self.get_goods(item)
            if goods:
                if goods['code'] == 200:
                    contents = goods['data']['content']
                    for content in contents:
                        if content['isSellOut']:
                            print("无货====" + content['name'])
                        else:
                            print("有货" + content['name'])
                            hasGoods.append(content['name'])
                else:
                    print(goods['msg'])
            time.sleep(5)
        return hasGoods

    def goods_detail(self, body_data, user_id="", user_token=""):
        params = self.get_base_params(body_data, user_id, user_token)
        url = self.goods_details_url + urlencode(params)
        json_obj = json.dumps(body_data)
        result = self.session.post(url, data=json_obj, headers=self.headers, verify=False)
        return result.text

    # 获取验证码
    def __get_img_captcha(self):
        params = self.get_base_params()
        url = self.img_captcha_url + urlencode(params)
        print(url)
        result = self.session.post(url, headers=self.headers, verify=False)
        return json.loads(result.text)

    """
    {
    "code": 200,
    "data": {
        "bigImg": "base64base64base64base64base64base64",
        "captchaId": "899143add4fa461ca4c252bc5653b6fd",
        "locX": 395,
        "locY": 66,
        "smallImg": "”
    },
    "msg": "success",
    "ts": 1618147862382
}
    """

    # 校验验证码
    def __validate_captcha(self, captcha_id, loc_x):
        body_data = {"captchaId": captcha_id, "locX": loc_x}
        params = self.get_base_params(body_data)
        url = self.validate_captcha_url + urlencode(params)
        print(url)
        json_obj = json.dumps(body_data)
        result = self.session.post(url, data=json_obj, headers=self.headers, verify=False)
        return json.loads(result.text)

    # 发送验证码
    def __send_img(self, mobile, captcha_id):
        body_data = {"mobile": mobile, "type": "LOGIN_CONFIRMATION", "captchaId": captcha_id}
        params = self.get_base_params(body_data)
        url = self.send_to_mobile_url + urlencode(params)
        print(url)
        json_obj = json.dumps(body_data)
        result = self.session.post(url, data=json_obj, headers=self.headers, verify=False).text
        r = json.loads(result)
        print('验证码发送成功' if r['code'] == 200 else '验证码发送失败')

    # 获取验证码/校验验证码/发送验证码
    def send_img(self, mobile):
        verification_code = self.__get_img_captcha()
        if verification_code and verification_code['code'] == 200:
            data = verification_code['data']
            num = random.random() / 4.0
            loc_x = data['locX'] + num
            print(num)
            result = self.__validate_captcha(data['captchaId'], loc_x)
            if result and result['code'] == 200:
                self.__send_img(mobile, verification_code['data']['captchaId'])
            print(result)

    def login(self):
        body_data = {"accountTypes": "MEMBER", "applicationType": "SMALL_PROGRAM", "password": None,
                     "phone": "19522969336", "verifyCode": "002031", "memberType": "COMMON",
                     "verifyType": "VERIFY_CODE", "authCode": "061Kbpll2wZSP64tzSkl2tGsNj1Kbpla",
                     "nickName": "light_rain", "country": "China", "province": "Hubei", "city": "Wuhan"}

        params = self.get_base_params(body_data)
        url = self.login_url + urlencode(params)
        print(url)
        json_obj = json.dumps(body_data)
        result = self.session.post(url, data=json_obj, headers=self.headers, verify=False).text
        r = json.loads(result)


7

if __name__ == '__main__':
    api = Api()
    api.send_img('19522969336')
